package Filters;

import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(filterName = "OnlineCheck" ,urlPatterns = "/*")
public class f2_OnlineCheck implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httprequest= (HttpServletRequest) request;
        HttpSession session=  httprequest.getSession();
        String url= httprequest.getRequestURI().substring(httprequest.getContextPath().length());
        Object user=session.getAttribute("user");
        //控制登录，如果从session获取到值就说明已经登录，否则不断重定向到登录页面
//        if (url.equals("/Register.jsp")||url.equals("/Login.jsp")){//且不说我要查看我别的页面不能靠改地址过去要登陆，他貌似把我登录也给拦截了
        if (url.equals("/Register.jsp")||url.equals("/Login.jsp")||url.equals("/login")||url.equals("/register")){
//        if(true){
            chain.doFilter(request,response);
            return ;
        }
        else if(user!=null){
            chain.doFilter(request,response);
            return ;
        }
        else{
            httprequest.getRequestDispatcher("Login.jsp").forward(request,response);
        }

    }
}
